import { useState, useEffect, createContext, useContext, useMemo } from 'react';
import { 
  getUserToken, 
  getUserInfo, 
  setUserToken, 
  setUserInfo, 
  removeUserToken,
  getAdminToken,
  getAdminUserInfo,
  setAdminToken,
  setAdminUserInfo,
  removeAdminToken
} from '../utils/auth';

// 创建认证上下文
const AuthContext = createContext();

// 认证Provider组件
export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // 初始化时检查本地存储的用户信息
    const token = getUserToken();
    const userInfo = getUserInfo();
    
    console.log('useAuth 初始化 - Token:', token);
    console.log('useAuth 初始化 - UserInfo:', userInfo);
    
    if (token && userInfo) {
      setUser(userInfo);
    }
    
    setLoading(false);
  }, []);

  // 登录
  const login = (token, userInfo) => {
    console.log('useAuth login 被调用');
    console.log('保存 token:', token);
    console.log('保存 userInfo:', userInfo);
    
    setUserToken(token);
    setUserInfo(userInfo);
    setUser(userInfo);
    
    console.log('useAuth login 完成');
  };

  // 登出
  const logout = () => {
    removeUserToken();
    setUser(null);
  };

  // 更新用户信息
  const updateUser = (userInfo) => {
    setUserInfo(userInfo);
    setUser(userInfo);
  };

  // 使用 useMemo 来计算 isAuthenticated，确保它是响应式的
  const isAuthenticated = useMemo(() => {
    const token = getUserToken();
    const hasValidUser = !!user;
    const result = !!token && hasValidUser;
    
    console.log('计算 isAuthenticated:', {
      token: !!token,
      hasValidUser,
      result
    });
    
    return result;
  }, [user]); // 依赖 user 状态

  // 检查权限
  const hasPermission = (permission) => {
    if (!user || !user.permissions) return false;
    
    // 超级管理员拥有所有权限
    if (user.roles?.some(role => role.code === 'super_admin')) {
      return true;
    }
    
    // 检查用户的权限列表
    return user.permissions.includes(permission);
  };

  // 检查角色
  const hasRole = (roleCode) => {
    if (!user || !user.roles) return false;
    return user.roles.some(role => role.code === roleCode);
  };

  const value = {
    user,
    loading,
    login,
    logout,
    updateUser,
    isAuthenticated, // 现在这是一个响应式的值
    hasPermission,
    hasRole
  };

  console.log('useAuth Provider 当前状态:', {
    user: !!user,
    loading,
    isAuthenticated
  });

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};

// 自定义Hook
export const useUserAuth = () => {
  const context = useContext(AuthContext);
  
  if (!context) {
    // 如果没有Provider，返回基本功能
    const user = getUserInfo();
    const token = getUserToken();
    
    return {
      user,
      loading: false,
      login: () => {},
      logout: () => {
        removeUserToken();
      },
      updateUser: () => {},
      isAuthenticated: !!token && !!user,
      hasPermission: (permission) => {
        if (!user || !user.permissions) return false;
        if (user.roles?.some(role => role.code === 'super_admin')) {
          return true;
        }
        return user.permissions?.includes(permission) || false;
      },
      hasRole: (roleCode) => {
        if (!user || !user.roles) return false;
        return user.roles.some(role => role.code === roleCode);
      }
    };
  }
  
  return context;
};

// 后台管理员认证Hook
export const useAdminAuth = () => {
  const [adminUser, setAdminUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // 初始化时检查本地存储的管理员信息
    const token = getAdminToken();
    const userInfo = getAdminUserInfo();
    
    if (token && userInfo) {
      setAdminUser(userInfo);
    }
    
    setLoading(false);
  }, []);

  // 管理员登录
  const adminLogin = (token, userInfo) => {
    setAdminToken(token);
    setAdminUserInfo(userInfo);
    setAdminUser(userInfo);
  };

  // 管理员登出
  const adminLogout = () => {
    removeAdminToken();
    setAdminUser(null);
  };

  // 更新管理员信息
  const updateAdminUser = (userInfo) => {
    setAdminUserInfo(userInfo);
    setAdminUser(userInfo);
  };

  // 检查管理员是否已认证
  const isAdminAuthenticated = useMemo(() => {
    const token = getAdminToken();
    const hasValidUser = !!adminUser;
    return !!token && hasValidUser;
  }, [adminUser]);

  // 检查管理员权限
  const hasAdminPermission = (permission) => {
    if (!adminUser || !adminUser.permissions) return false;
    
    // 超级管理员拥有所有权限
    if (adminUser.roles?.some(role => role.code === 'super_admin')) {
      return true;
    }
    
    // 检查管理员的权限列表
    return adminUser.permissions.includes(permission);
  };

  // 检查管理员角色
  const hasAdminRole = (roleCode) => {
    if (!adminUser || !adminUser.roles) return false;
    return adminUser.roles.some(role => role.code === roleCode);
  };

  return {
    user: adminUser,
    loading,
    login: adminLogin,
    logout: adminLogout,
    updateUser: updateAdminUser,
    isAuthenticated: isAdminAuthenticated,
    hasAdminPermission: hasAdminPermission,
    hasAdminRole: hasAdminRole
  };
};